package com.berchen.test;

import java.util.concurrent.*;

/**
 * 线程池的使用
 */
public class ThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        // 异步执行
        CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> {

            System.out.println(Thread.currentThread().getName() + "异步执行1");
        }, threadPoolExecutor);

        CompletableFuture<Void> runAsync1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "异步执行2");
        }, threadPoolExecutor);

        // 等待上面异步执行执行完成 可以等待多个 必须得等上面的两个异步任务执行完成才能执行下面的事情
        CompletableFuture.allOf(runAsync1,runAsync).get();  // 不等待的话 上面两个和main就会随机执行
        System.out.println("执行完成");
        threadPoolExecutor.shutdown();
    }
}
